#include "app_runner.h"
#include "app_device.h"
#include "app_mqtt.h"
#include "app_bt.h"
#include "app_serial.h"
#include "app_pool.h"
#include "log.h"
#include <signal.h>
#include <unistd.h>


static is_running=1;


/**
 * @brief 网关主程序启动
 * 
 */

 void app_runner_stop(int sig)
 {
    is_running=0;
 }
 


 int app_runner_start()
 {
    log_set_level(LOG_INFO);

    //0 注册信号处理函数
    signal(SIGINT,app_runner_stop); //ctrl+c
    signal(SIGTERM,app_runner_stop); //kill

    //1 初始化 消息队列模块
    int ret= app_mqtt_init();
    if(ret==0)
    {
        log_info("app_mqtt_init success");
    }else{
        return -1;
    }
    //2 初始化 线程池模块
    ret=app_pool_init();
    if(ret==0)
    {
        log_info("app_pool_init success");
    }else{
        return -1;
    }
    //3 初始化 设备模块
    app_device_t *device =app_device_init();
    if(device !=NULL)
    {
        log_info("app_device_init success");
    }else{
        return -1;
    }
    //4  为设备进行 串口设置
    ret= app_serial_init(device);
    if(ret==0)
    {
        log_info("app_serial_init success");
    }else{
        return -1;
    }

    //5  为设备进行 蓝牙设置
    ret= app_bt_init(device);
    if(ret==0)
    {
        log_info("app_bt_init success");
    }else{
        return -1;
    }
    //6  设备模块启动
    ret= app_device_start(device);
    if(ret==0)
    {
        log_info("app_device_start success");

    }else{
        return -1;
    }

    while(is_running)
    {
        sleep(1);
    }
    //释放资源
    app_device_destroy();
    app_mqtt_destroy();
    app_pool_destroy();

    printf("app_runner_start success");
    return 0;




 }